﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wicresoft.SMS.Data
{
    public class UserService : IUserService
    {
        private IConnectStringProvider icsp;

        public UserService(IConnectStringProvider _icsp)
        {
            this.icsp = _icsp;
        }

        public User GetUserItemByCIL(string cil)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var user = dbacc.User.FirstOrDefault(a => a.CIL == cil);
                return user;
            }
        }


        public bool CreateOrUpdateUser(User user)
        {
            try
            {
                using (var dbacc = new Entities(icsp.ConnectionString))
                {
                    var temp = dbacc.User.FirstOrDefault(a => a.CIL == user.CIL);
                    if (temp != null)
                    {
                        temp.NameCN = user.NameCN;
                        temp.NameEN = user.NameEN;
                        temp.Email = user.Email;
                        temp.IsActive = user.IsActive;
                        temp.DepartmentID = user.DepartmentID;
                        temp.Mobile = user.Mobile;
                    }
                    else
                    {
                        Role role = dbacc.Role.FirstOrDefault(a => a.RoleID == 3);
                        if (role != null)
                            user.Role.Add(role);
                        dbacc.AddToUser(user);                        
                    }
                    dbacc.SaveChanges();                   

                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }           
        }
    }
}
